var express = require("express");
var router = express.Router();
var utils = require('../utils/index');
var mysql = require("../connect/index");
var connection = require("../connect/mysql");

var { Agents, AgentsAuth } = require('../models/shop/agents.model');

router.get("/", function (req, res, next) {
    res.send(utils.setSendResult());
});


// 获取代理商信息
router.get("/list", function (req, res, next) {
    const query = req.query;
    Agents.findAll().then(result => {
        res.send(utils.setSendResult(200, "查询成功", result));
    }).catch(err => {
        res.send(utils.setSendResult(500, err));
    }).finally(async () => {
    //    await mysql.sequelize.close();
    });
});
// 新增代理商信息
router.post("/add", function (req, res, next) {
    const params = req.body;
    Agents.create(params).then(result => {
        res.send(utils.setSendResult(200, "添加成功", result));
    }).catch(err => {
        res.send(utils.setSendResult(500, err));
    }).finally(async () => {
       await mysql.sequelize.close();
    });
  
});
// 批量新增订单表 - 执行 sql 语句
router.get("/mock/sql", async (req, res, next) => {
    // 假设有两个表的数据
    const shop_orders = [
        { userid: '01', address: '丰台区', money: '2000', agentid: 4, contract: '1000000001', phone: '15212134582', state: 1, carryid: 1, remark: '备注信息' },
        { userid: '02', address: '海淀区', money: '2000', agentid: 5, contract: '1000000001', phone: '15212134582', state: 2, carryid: 2, remark: '备注信息' },
        { userid: '03', address: '昌平区', money: '2000', agentid: 6, contract: '1000000001', phone: '15212134582', state: 3, carryid: 3, remark: '备注信息' },
        { userid: '04', address: '朝阳区', money: '2000', agentid: 7, contract: '1000000001', phone: '15212134582', state: 4, carryid: 4, remark: '备注信息' },
        { userid: '05', address: '丰台区', money: '2000', agentid: 4, contract: '1000000001', phone: '15212134582', state: 1, carryid: 5, remark: '备注信息' },
        { userid: '06', address: '丰台区', money: '2000', agentid: 4, contract: '1000000001', phone: '15212134582', state: 3, carryid: 6, remark: '备注信息' },
        // 更多行...
    ];
    const shop_orders_flow = [{
        orderid: 1, prestate: 1, state: 2, operator: '1000000001', remark: '备注信息'
    }, {
        orderid: 2, prestate: 2, state: 3, operator: '1000000001', remark: '备注信息'
    }, {
        orderid: 3, prestate: 3, state: 4, operator: '1000000001', remark: '备注信息'
    }, {
        orderid: 4, prestate: 4, state: 5, operator: '1000000001', remark: '备注信息'
    }, {
        orderid: 5, prestate: 5, state: 6, operator: '1000000001', remark: '备注信息'
    }]
    try {
        // 开始事务
        connection.beginTransaction((err) => {
            if (err) {
                console.log('BEGIN TRANSACTION ERROR - ', err.message);
                throw err
            }
            // 批量插入主表数据
            const insertQuery1 = 'INSERT INTO shop_orders (userid,address,money,agentid,contract,phone,state,carryid,remark) VALUES ?';
            connection.query(insertQuery1, [shop_orders.map(row => [row.userid, row.address, row.money, row.agentid, row.contract, row.phone, row.state, row.carryid, row.remark])], (error, results, fields) => {
                if (error) {
                    return connection.rollback(() => {
                        throw error;
                    });
                }
                // 获取刚插入行的自增ID
                const lastInsertedId = results.insertId;
                // 第二步：利用获取到的ID向副表插入数据
                // 批量插入第二个表
                const insertQuery2 = 'INSERT INTO shop_orders_flow (orderid,prestate,state,operator,remark) VALUES ?';
                const values = shop_orders_flow.map(row => [row.orderid, row.prestate, row.state, row.operator, row.remark]);
                connection.query(insertQuery2, [values], (error2) => {
                    if (error2) {
                        return connection.rollback(() => {
                            throw error;
                        });
                    }
                    // 如果所有操作均无误，则提交事务
                    connection.commit((err3) => {
                        if (err3) {
                            return connection.rollback(() => {
                                throw err3;
                            });
                        }
                        res.send(utils.setSendResult(200, "批量添加成功", results));
                        connection.end();
                    });
                });
            })
        });
    } catch (err) {
        // 有错误时回滚
        await connection.rollback();
        throw err;
    }
})
// 批量新增代理商信息 - 执行 sql 语句
router.get("/mock/sqlOne", async (req, res, next) => {
    // var datas = [{
    //     name:"北京代理商", account:'110929202028834', contacts:'李晓明', phone:'15212134582', bankcard:'622578421111134555', authinfo:'申购产品'
    // },{
    //     name:"天津代理商", account:'110929202028836', contacts:'王晓华', phone:'15212134582', bankcard:'622578421111134555', authinfo:'售卖产品'
    // },{
    //     name:"华北代理商", account:'110929202028838', contacts:'张小英', phone:'15212134582', bankcard:'622578421111134555', authinfo:'维修产品'
    // },{
    //     name:"北京代理商", account:'110929202028834', contacts:'李晓明', phone:'15212134582', bankcard:'622578421111134555', authinfo:'申购产品'
    // },{
    //     name:"天津代理商", account:'110929202028836', contacts:'王晓华', phone:'15212134582', bankcard:'622578421111134555', authinfo:'售卖产品'
    // },{
    //     name:"华北代理商", account:'110929202028838', contacts:'张小英', phone:'15212134582', bankcard:'622578421111134555', authinfo:'维修产品'
    // },{
    //     name:"北京代理商", account:'110929202028834', contacts:'李晓明', phone:'15212134582', bankcard:'622578421111134555', authinfo:'申购产品'
    // },{
    //     name:"天津代理商", account:'110929202028836', contacts:'王晓华', phone:'15212134582', bankcard:'622578421111134555', authinfo:'售卖产品'
    // },{
    //     name:"华北代理商", account:'110929202028838', contacts:'张小英', phone:'15212134582', bankcard:'622578421111134555', authinfo:'维修产品'
    // },{
    //     name:"华北代理商", account:'110929202028838', contacts:'张小英', phone:'15212134582', bankcard:'622578421111134555', authinfo:'维修产品'
    // }]
    try {
        const data = [
            {
                address: '北京市西三环中路', agentid: 4
            }, {
                address: '天津市西二环中路', agentid: 5
            }, {
                address: '南昌市', agentid: 6
            }
        ]
        const values = data.map(item => [item.agentid, item.address]);
        var insertsql = 'insert into shop_agents_auth(agentid, address) values ?'
        connection.query(insertsql, [values], (err, results, fields) => {
            if (err) {
                console.log('INSERT ERROR - ', err.message);
                throw err
            }
            connection.destroy();
            res.send(utils.setSendResult(200, "批量添加成功", results));
        })
    } catch (error) {
        console.error('批量插入失败:', error);
    }
    // Agents.bulkCreate({
    //     datas,
    //     'shop_agents_auth': [{
    //         address:'北京市西三环中路', agentid: 4
    //     },{
    //         address:'天津市西二环中路', agentid: 5
    //     },{
    //         address:'南昌市', agentid: 6
    //     }]
    // }, {
    //     include: [AgentsAuth]
    // }).then(result=>{
    //     res.send(utils.setSendResult(200, "批量添加成功", result));
    // }).catch(error => {
    //     console.error('批量插入失败:', error);
    // });
});
// 修改代理商信息
router.post("/edit", function (req, res, next) {
    const params = req.body;
    if (params['id'] == undefined) return res.send(utils.setSendResult(400, "参数错误", {}));
    Agents.update(params).then(result => {
        res.send(utils.setSendResult(200, "修改成功", result));
    }).catch(err => {
        res.send(utils.setSendResult(500, err));
    }).finally(async () => {
       await mysql.sequelize.close();
    });
});
// 删除代理商信息
router.get("/delete", function (req, res, next) {
    const query = req.query;
    if (query['id'] == undefined) return res.send(utils.setSendResult(400, "参数错误", {}));
    Agents.destroy({
        where: {
            id: query['id']
        }
    }).then(result => {
        res.send(utils.setSendResult(200, "删除成功", result));
    }).catch(err => {
        res.send(utils.setSendResult(500, err));
    }).finally(async () => {
       await mysql.sequelize.close();
    });
    
});

// 代理商详细信息
module.exports = router;
